package com.nitty.cash.loop.ui.activity

import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.Permission
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.common.CommonFragment
import com.nitty.cash.loop.databinding.UiPermissionsBinding
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.fragment.PermissionFragment
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.PermissionPresenter
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import com.nitty.cash.loop.utils.helper.NittyAnalysisHelper
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:04
 * @Annotation：权限
 */
class PermissionsAct: CommonActivity(), IViewContract.IPermissionView {
    lateinit var binding: UiPermissionsBinding
    var isFirstIn = true

    var presenter: PermissionPresenter? = null
    private var pageList: ArrayList<CommonFragment>? = null

    override fun getNittyRootView(): View? {
        binding = UiPermissionsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        NittyTitleBarUtil.setStatusBarLightMode(this, false)
        pageList = arrayListOf()
    }

    override fun initNittyListener() {
        binding.permissionViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (!isFirstIn){
                    presenter?.onUserPermissionCheckPageClick(position)
                }
            }
        })

//        binding.permissionLast.setOnClickListener {
//            if (presenter!!.curtIndex == 0){
//                return@setOnClickListener
//            }
//            val showIndex = presenter!!.curtIndex - 1
//            binding.permissionViewPager.currentItem = showIndex
//        }

//        binding.permissionNext.setOnClickListener {
//            if (presenter!!.curtIndex == presenter!!.getUserPermissionList().size - 1){
//                return@setOnClickListener
//            }
//            val showIndex = presenter!!.curtIndex + 1
//            binding.permissionViewPager.currentItem = showIndex
//        }

        binding.checkBoxPermission.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> {
                    binding.btnPermissionAgree.isEnabled = true
                }
                false -> {
                    binding.btnPermissionAgree.isEnabled = false
                }
            }
        }
        //拒绝
        binding.btnPermissionDeny.setOnClickListener {
            presenter?.onUserPermissionDenyClick()
        }

        //同意权限
        binding.btnPermissionAgree.setOnClickListener {
            presenter?.onUserPermissionAgreeClick()
        }

        //已授权
        binding.btnPermissionAuthorized.setOnClickListener{
        }

        //被禁止
        binding.btnPermissionBanned.setOnClickListener {
            presenter?.onUserPermissionBannedClick()
        }
    }

    override fun loadNittyData() {
        if (presenter == null){
            presenter = PermissionPresenter(this)
        }
        presenter?.loadUserPermissionListAction()
    }

    override fun onResume() {
        super.onResume()
        if (!isFirstIn){
            presenter?.onUserPermissionResume()
        }
    }

    /**
     * 设置权限列表
     */
    override fun showPermissionList(pList: ArrayList<JSONObject>) {
        pList.forEach {
            pageList?.add(PermissionFragment(it))
        }
        val pageAdapter = PermissionPagerAdapter(this,pageList!!)
        binding.permissionViewPager.adapter = pageAdapter
    }

    /**
     * 设置显示权限
     */
    override fun showPermissionPage(index: Int) {
        isFirstIn = false
        binding.permissionViewPager.currentItem = index

        val item = presenter!!.getUserPermissionList()[index]
        binding.imgPermissionIcon.setImageResource(item.optInt("icon"))
        binding.textPermissionTitle.text = item.optString("title")
        binding.textPermissionTitle.setTextColor(item.optInt("titleColor"))
    }

    /**
     * 未申请
     */
    override fun showPermissionNotObtained() {
        binding.permissionBtnLayout.visibility = View.VISIBLE
        binding.btnPermissionAuthorized.visibility = View.GONE
        binding.btnPermissionBanned.visibility = View.GONE

        binding.tipsPermissionLayout.visibility = View.VISIBLE

        binding.checkBoxPermission.isChecked = true
        binding.btnPermissionAgree.isEnabled = true
    }

    /**
     * 已允许
     */
    override fun showPermissionAuthorized() {
        binding.permissionBtnLayout.visibility = View.GONE
        binding.btnPermissionAuthorized.visibility = View.VISIBLE
        binding.btnPermissionBanned.visibility = View.GONE

        binding.tipsPermissionLayout.visibility = View.GONE
    }

    /**
     * 已拒绝
     */
    override fun showPermissionBanned() {
        binding.permissionBtnLayout.visibility = View.GONE
        binding.btnPermissionAuthorized.visibility = View.GONE
        binding.btnPermissionBanned.visibility = View.VISIBLE

        binding.tipsPermissionLayout.visibility = View.GONE
    }

    /**
     * 进入登录页面
     */
    override fun showPermissionSuccess() {
        //已同意 READ_PHONE_STATE 权限，代表已经进入过权限声明页面
        if (CommonPermissions.isGranted(this, Permission.READ_PHONE_STATE)){
            NittySharedHelper.putNittySharedData(NittySharedKey.NITTY_SHOW_PERMISSION_LAUNCH_PAGE,true)
        }
        //已登录
        if (NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            NittyAnalysisHelper.initAnalysisLibAtLoginSuccess()
            onIntent(NittyTabAct::class.java)
        } else {
            onIntent(LoginAct::class.java)
        }
        finish()
    }


    class PermissionPagerAdapter(fragmentActivity: FragmentActivity, private val pageList: ArrayList<CommonFragment>) : FragmentStateAdapter(fragmentActivity) {
        override fun createFragment(position: Int): Fragment {
            return pageList[position]
        }
        override fun getItemCount(): Int {
            return pageList.size
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_PERMISSION_PHONE_STATE_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_PERMISSION_PHONE_STATE_END)
    }
}